<template>
  <!-- 评审专家名单(监管可以查看与修改) -->
  <div class="review-experts-list-content" v-if="userRoles.includes(100) && pageConfig.form.flowNode == props.process">
    <!-- 标题 -->
    <div class="review-experts-list-content-title">
      评审专家名单
      <el-tooltip content="蓝色代表启用中的专家,黑色代表停用中的专家" placement="top">
        <el-icon><question-filled /></el-icon>
      </el-tooltip>
    </div>
    <!-- 专家名单 -->
    <div class="review-experts-list-content-list">
      <!-- 专家 -->
      <div v-for="(item, index) in pageConfig.expertsList" :key="index" class="review-experts-list-content-list-item" :class="{ enable: item.state == 0 }">
        {{ item.createName }}
      </div>
      <!-- 选择专家 -->
      <div class="review-experts-list-content-list-button">
        <el-button type="primary" @click="handleExpertManagement">专家管理</el-button>
      </div>
    </div>
  </div>

  <!-- 对话框 专家选择 -->
  <el-dialog v-model="pageConfig.expertManagementOpen" title="专家管理" width="850px">
    <el-form :model="pageConfig.expertManagementForm" ref="expertManagementRef" label-width="140px" :rules="pageConfig.rules">
      <!-- 循环专家 禁用停用 添加专家 -->
      <el-form-item label="选择评审专家" prop="zhuanjia" style="width: 100%">
        <div class="expert-list-content">
          <div class="expert-list-content-list">
            <div class="expert-list-content-item" v-for="(item, index) in pageConfig.expertManagementForm.expertAssociationMultis" :key="index" :class="{ enable: item.state == 0 }">
              <div>{{ item.createName }}</div>
              <div v-show="item.state == 1">
                <!-- 启用（限制：最多同时启用5个 -->
                <el-button type="success" @click="handleActivateExperts(item)">启用</el-button>
              </div>
              <div v-show="item.state == 0">
                <!-- 停用没限制 -->
                <el-button type="info" @click="handleStopUsingExperts(item)">停用</el-button>
              </div>
            </div>
          </div>
          <div class="expert-list-content-add">
            <el-button type="primary" plain @click="handleAddExpert">添加专家</el-button>
          </div>
        </div>
      </el-form-item>
      <!-- 组长 -->
      <!-- :disabled="pageConfig.form.flowNode != 'C'" -->

      <el-form-item label="评审专家组长" prop="expertId" style="width: 100%">
        <el-select v-model="pageConfig.expertManagementForm.expertId" placeholder="评审专家组长" style="width: 100%" clearable @change="handleSelectTeamLeader">
          <el-option v-for="expertItem in enableExpertMonumentInstallation" :key="expertItem.expertId" :label="expertItem.createName" :value="expertItem.expertId"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm(expertManagementRef)" :loading="pageConfig.submitLoading">确 定</el-button>
        <el-button @click="handleClose">取 消</el-button>
      </div>
    </template>
    <!-- 选择评审专家 弹窗 -->
    <selectExpert v-model:open="pageConfig.selectExpertOpen" @selectExpert="handleSelectExpert" />
  </el-dialog>
</template>

<script setup name="expertInfo">
import useUserStore from "@/store/modules/user";
import selectExpert from "@/components/selectExpert/index.vue";
import { getExpertsList, getInfoByFlowId } from "@/api/flowInfo/info";
import { addMultiList } from "@/api/associationMulti/multi.js";
const { proxy } = getCurrentInstance();
const userStore = useUserStore();
import { nextTick, reactive } from "vue";
const pageConfig = reactive({
  // 遮罩层
  loading: false,
  submitLoading: false,
  // 选中数组
  ids: [],
  // 子表选中数据
  checkedExpertCertificates: [],
  // 非单个禁用
  single: true,
  // 非多个禁用
  multiple: true,
  // 显示搜索条件
  showSearch: true,
  // 总条数
  total: 0,
  // 表格数据
  dataList: [],
  // 弹出层标题
  title: "",
  // 是否显示弹出层
  open: false,
  expertManagementOpen: false,
  selectExpertOpen: false,
  // 查询参数
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  },
  // 表单参数
  form: {},
  // 表单校验
  rules: {
    zhuanjia: [
      {
        validator: (rule, value, cb) => {
          const length = pageConfig.expertManagementForm.expertAssociationMultis.filter((item) => item.state == "0").length;
          if (length < 3) {
            cb(new Error("启用的评审专家不能低于三位"));
          } else if (length > 5) {
            cb(new Error("启用的评审专家不能超过五位"));
          } else {
            cb();
          }
        },
      },
    ],
    expertId: [
      {
        validator: (rule, value, cb) => {
          if (pageConfig.expertManagementForm.expertId) {
            cb();
          } else {
            cb(new Error("清选择评审专家组长"));
          }
        },
      },
    ],
  },
  // 专家列表
  expertsList: [],
  // 专家管理 修改
  expertManagementForm: {
    expertAssociationMultis: [],
  },
});
const route = useRoute();
const emit = defineEmits(["refresh"]);
const props = defineProps({
  flowNode: {
    type: String,
    default: "",
  },
  process: {
    type: String,
    default: "",
  },
  step: {
    type: String,
    default: "",
  },
});
// 用户角色
const userRoles = computed(() => {
  const roles = JSON.parse(JSON.stringify(userStore.userRoles));
  if (roles.length) {
    const name = roles.map((item) => {
      return item.roleName;
    });
    return roles.map((item) => {
      return item.roleId;
    });
  } else {
    return [];
  }
});
/** 查询流程详情 */
function getInfo() {
  if (!userRoles.value.includes(100)) return;
  const flowId = route.query.flowId;
  // 查看详情回显
  const param = {
    flowId: flowId,
    flowNode: props.flowNode,
    step: props.step,
  };

  getInfoByFlowId(param).then((response) => {
    pageConfig.form = response.data;
  });
}
getInfo();
// 获取流程中的专家数量
function getExpertsListFn() {
  // 只有监管才能获取列表，并显示
  if (!userRoles.value.includes(100)) return;
  getExpertsList({
    flowId: route.query.flowId,
    flowType: props.flowNode,
    pageNum: 1,
    pageSize: 999,
  }).then((res) => {
    pageConfig.expertsList = res.rows;
  });
}
getExpertsListFn();

// 专家管理
function handleExpertManagement() {
  // 赋值弹窗内新列表
  pageConfig.expertManagementForm.expertAssociationMultis = pageConfig.expertsList;
  // 打开弹窗
  pageConfig.expertManagementOpen = true;
  // 计算专家组长对象
  const objExpert = pageConfig.expertManagementForm.expertAssociationMultis.find((it) => it.groupLeader == 1);
  pageConfig.expertManagementForm.expertId = objExpert.expertId;
}

// 专家管理 启用专家
function handleActivateExperts(item) {
  const length = pageConfig.expertManagementForm.expertAssociationMultis.filter((item) => item.state == "0").length;
  if (length >= 5) {
    proxy.$modal.msgWarning("最多同时启用 5 个专家");
    return;
  }
  item.state = 0;
}
// 专家管理 停用专家
function handleStopUsingExperts(item) {
  item.state = 1;
  // 判断如果停用的是组长，那么就置空组长id
  if (item.groupLeader == 1) {
    nextTick(() => {
      item.groupLeader = 0;
      pageConfig.expertManagementForm.expertId = "";
    });
  }
}
// 专家管理 添加专家
function handleAddExpert() {
  pageConfig.selectExpertOpen = true;
}
// 专家管理 添加专家 确认选择回调
function handleSelectExpert(val) {
  // 选择的专家
  let selectExpertList = val.map((it) => {
    return {
      ...it,
      createName: it.realName,
      expertId: it.userId,
      state: "1", //默认加入的停用
      groupLeader: 0,
    };
  });
  let zongList = [...pageConfig.expertManagementForm.expertAssociationMultis, ...selectExpertList];

  const independentList = zongList.reduce((accumulator, current) => {
    if (!accumulator.find((item) => item.expertId === current.expertId)) {
      accumulator.push(current);
    }
    return accumulator;
  }, []);
  // 赋值唯一的专家项
  pageConfig.expertManagementForm.expertAssociationMultis = independentList;
}
// 专家管理-评审专家组长 列表（只筛选启用状态的）
const enableExpertMonumentInstallation = computed(() => {
  let list = pageConfig.expertManagementForm.expertAssociationMultis;
  if (!list.length) return [];
  return list.filter((it) => it.state == "0");
});
// 专家管理-选择专家（防止变量泄漏，调用就赋空groupLeader为0
function handleSelectTeamLeader() {
  pageConfig.expertManagementForm.expertAssociationMultis.forEach((item) => {
    if (item.groupLeader == 1) item.groupLeader = 0;
    nextTick(() => {
      if (item.expertId == pageConfig.expertManagementForm.expertId) {
        item.groupLeader = 1;
      }
    });
  });
}
// 表单实例
const expertManagementRef = ref();
// 专家管理 确认 (修改流程专家，并刷新状态)
function submitForm(formEl) {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      pageConfig.submitLoading = true;
      let list = JSON.parse(JSON.stringify(pageConfig.expertManagementForm.expertAssociationMultis));
      addMultiList(
        list.map((it) => {
          return {
            ...it,
            realName: it.createName,
            userId: it.expertId,
            flowId: route.query.flowId,
            flowType: props.flowNode, //流程
          };
        })
      )
        .then((response) => {
          if (response.code == 200) {
            proxy.$modal.msgSuccess("操作成功！");
            pageConfig.expertManagementOpen = false;
            getExpertsListFn();
            emit("refresh");
          }
        })
        .finally(() => {
          pageConfig.submitLoading = false;
        });
    }
  });
}
// 专家管理 关闭弹窗
function handleClose() {
  pageConfig.expertManagementOpen = false;
}
</script>
<style scoped lang="scss">
//评审专家名单
.review-experts-list-content {
  display: flex;
  padding: 40px 42px;
  padding-bottom: 18px;
  box-sizing: border-box;
  min-height: 30px;
  // align-items: center;
  align-items: flex-start;
  .review-experts-list-content-title {
    width: 140px;
    font-weight: 600;
    font-size: 16px;
    color: #1a75ff;
    display: flex;
    align-items: center;
    min-height: 30px;
    line-height: 30px;
  }

  .review-experts-list-content-list {
    width: calc(100% - 120px);
    display: flex;
    flex-wrap: wrap;
    gap: 19px;
    min-height: 30px;
    line-height: 30px;
    .review-experts-list-content-list-item {
      font-weight: 400;
      font-size: 16px;
      color: #3d3d3d;
      &.enable {
        color: #1a75ff;
      }
    }
    .review-experts-list-content-list-button {
      width: 80px;
      height: 30px;
      background: #1a75ff;
      border-radius: 6px;

      font-weight: 700;
      font-size: 14px;
      color: #ffffff;
    }
  }
}
// 专家管理弹窗
.expert-list-content {
  display: flex;
  // align-items: center;
  flex-direction: column;
  width: 100%;
  .expert-list-content-list {
    display: flex;
    flex-direction: column;
    max-height: 400px;
    overflow-y: auto;
    .expert-list-content-item {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      cursor: pointer;
      height: 34px;
      font-weight: 400;
      font-size: 18px;
      color: #3d3d3d;
      line-height: 25px;
      white-space: nowrap;
      margin-bottom: 20px;

      &.enable {
        color: #1a75ff;
      }
    }
  }
  .expert-list-content-add {
    margin-left: auto;
  }
}
</style>
